﻿local _, ns = ...

local DefaultSpecialAuras = ns.RightAuras
--图标数量
local RightAurasMax = ns.RightAuraMax
local RightAurasSize = ns.RightAuraSize

--设置图标
local function SetRightFrameParameters(frame, aura)

    frame.Texture:SetTexture(aura.icon)
	frame.Texture:SetTexCoord(0.1,0.9,0.1,0.9)
	if PlateColorDB.RightAuraTip then 
		frame:SetScript("OnEnter", function(self)
			if PlateColorDB.hpAuraToLeft then
				GameTooltip:SetOwner(frame, "ANCHOR_CURSOR_LEFT",-20,-100)
			else
				GameTooltip:SetOwner(frame, "ANCHOR_CURSOR_RIGHT",20,-100)
			end
			GameTooltip:SetSpellByID(aura.spellId)
			GameTooltip:Show()
		end)
		frame:SetScript("OnLeave", function(self)
			GameTooltip:Hide()
		end)
	end
	
    frame.count:SetText(aura.applications > 1 and aura.applications or "")
    
    CooldownFrame_Set(frame.Cooldown, aura.expirationTime - aura.duration, aura.duration, aura.duration > 0, true)
	frame.Cooldown:SetHideCountdownNumbers(aura.duration>99)
    
    frame:Show()
	
	if LibStub and LibStub("LibCustomGlow-1.0", true) then
		if aura.dispelName == "Magic" then
			LibStub("LibCustomGlow-1.0").PixelGlow_Start(frame,{0,1,0,1},nil,.25,nil,2)
		elseif aura.dispelName == "" then
			LibStub("LibCustomGlow-1.0").PixelGlow_Start(frame,{1,0,0,1},nil,.25,nil,2)
		else
			LibStub("LibCustomGlow-1.0").PixelGlow_Start(frame,{1,1,1,1},nil,.25,nil,2)
		end
	end
	
end

--创建图标
local function AddRightFrame(unitFrame, aura,delete)

	--先延迟更新箭头
	if not PlateColorDB.hpAuraToLeft then
		C_Timer.After(0.1,function()
			if not ns.RightArrow then return end
			ns.RightArrow(unitFrame)
		end)
	else--在左边的话更新吸收盾位置
		C_Timer.After(0.1,function()
			if not ns.absUpdatePoint then return end
			ns.absUpdatePoint(unitFrame)
		
			--更新标记位置
			for i = ns.RightAuraMax,1,-1 do
				if unitFrame["RightAuras"..i] and unitFrame["RightAuras"..i]:IsShown() then
					unitFrame.RaidTargetFrame:SetPoint("RIGHT", unitFrame.healthBar, "LEFT", -1*(i * (ns.RightAuraSize+ns.RightAuraSize/15))-3, 0)
					break
				else
					unitFrame.RaidTargetFrame:SetPoint("RIGHT", unitFrame.healthBar, "LEFT", -15, 0)
				end
			end
		end)
	end

	--判断新增和删除
	if aura == 0 or delete then
		for i = 1, RightAurasMax do
			local frame = unitFrame["RightAuras"..i]
			if frame and frame:IsShown() and (aura == 0 or (delete and frame:GetID() == aura.spellId)) then
			--如果是新增和删除那么就删除隐藏对应的光环
				frame:Hide()
				frame:SetID(1)
				frame.auraInstanceID = nil
			end
		end
		return
	end
	
	if not aura then return end
	
    --如果已有相同的spellId,把他隐藏掉,后面重新设置可以让位置靠前
    for i = 1, RightAurasMax do
        local frame = unitFrame["RightAuras"..i]
        if frame and frame:IsShown() and frame:GetID() == aura.spellId then
			frame:Hide()
        end
    end
	
    -- 查找一个空闲的框架位置
    for i = 1, RightAurasMax do
        local frame = unitFrame["RightAuras"..i]

        if not frame then
		--如果没有框架创建新框架
            frame = CreateFrame("Frame", "RightAuras"..i, unitFrame.healthBar)
            unitFrame["RightAuras"..i] = frame
            frame:SetSize(RightAurasSize, RightAurasSize)
			if PlateColorDB.hpAuraToLeft then
				frame:SetPoint("RIGHT", unitFrame.healthBar, "LEFT", -1*((i-1)*(RightAurasSize+(RightAurasSize/15)) + 3), 3)
			else
				frame:SetPoint("LEFT", unitFrame.healthBar, "RIGHT", (i-1)*(RightAurasSize+(RightAurasSize/15)) + 3, 3)
			end
            frame:Hide()
            frame:SetID(aura.spellId)
			frame.auraInstanceID = aura
            frame.Texture = frame:CreateTexture(nil, "OVERLAY")
            frame.Texture:SetAllPoints()

            frame.count = frame:CreateFontString(nil, "ARTWORK")
            frame.count:SetFont(STANDARD_TEXT_FONT, RightAurasSize*0.8, 'OUTLINE')
            frame.count:SetPoint("BOTTOM", frame, "TOP", 0, -2)

            frame.Cooldown = CreateFrame("Cooldown", nil, frame, "CooldownFrameTemplate")
            frame.Cooldown:SetAllPoints()

            local region = frame.Cooldown:GetRegions()
            if region.GetText then
                region:SetFont(STANDARD_TEXT_FONT, RightAurasSize/2, "OUTLINE")
            end
            frame.Cooldown:SetReverse(true)
			frame.Cooldown:SetScript("OnCooldownDone", function(self)
				frame:Hide()
				
				--光环结束延迟一下更新箭头位置
				if not PlateColorDB.hpAuraToLeft then
					--C_Timer.After(0.1,function()
						if not ns.RightArrow then return end
						ns.RightArrow(unitFrame)
					--end)
				else--在左边的话更新吸收盾位置
					--C_Timer.After(0.1,function()
						if not ns.absUpdatePoint then return end
						ns.absUpdatePoint(unitFrame)
					--end)
				end
				
				--光环结束重新从表里更新一次光环
				--C_Timer.After(0.1,function()
					for key,aura in pairs(unitFrame.RightAuras) do
						AddRightFrame(unitFrame,aura)
					end
				--end)
			end)
			
        end
		
        if not frame:IsShown() then
		--如果没显示那就给这个框架设置参数
            frame:SetID(aura.spellId)
			frame.auraInstanceID = aura
            SetRightFrameParameters(frame, aura)
            return
        end
    end
	----------------------------------------------------------------
	
	
end

--过滤器
local function filter(aura,unit)
	if not UnitCanAttack("player",unit) then return end
	if UnitIsUnit("player", unit) then return end
	local dispelName = aura.isHelpful and (aura.dispelName == "Magic" or aura.dispelName == "" )
	local rightdot = DefaultSpecialAuras[aura.spellId]
	
	if aura.duration > 600 then return end--屏蔽大于10分钟的buff
	if dispelName or rightdot then
		return true
	end
end

--初始化
local function init(unitFrame)
	unitFrame.RightAuras = {}
	AddRightFrame(unitFrame, 0)
	local function HandleAura(aura)
		if filter(aura,unitFrame.unit) then
			unitFrame.RightAuras[aura.auraInstanceID] = aura;
			AddRightFrame(unitFrame,aura)
		end
		return false;
	end
	AuraUtil.ForEachAura(unitFrame.unit, "HARMFUL", nil, HandleAura,true)
	AuraUtil.ForEachAura(unitFrame.unit, "HELPFUL", nil, HandleAura,true)
end

local HDGUID = {}--麦卡贡车间-护盾发生器GUID统计,防止刷新计时

--刷新光环
local function UpdateAuras(self, event, unit,unitAuraUpdateInfo)
	if not PlateColorDB.hpRightAura then return end
	local namePlate = C_NamePlate.GetNamePlateForUnit(unit,false)
	if not namePlate then return end
	local unitFrame = namePlate.UnitFrame
	if unitFrame:IsForbidden() then return end
	
	if event == "NAME_PLATE_UNIT_ADDED" then
		init(unitFrame)
		--麦卡贡车间-护盾发生器结束倒计时
		local guid = UnitGUID(unitFrame.unit)
		local _, _, _, _, _, id = strsplit("-", guid or "") 
		if id == "151579" then
			if HDGUID[guid] then return end
			HDGUID[guid] = true
			local aura = {
				["icon"]=252184,--倒计时图标
				["applications"] = 1,
				["auraInstanceID"]=10,
				["spellId"]=358558,--倒计时法术ID
				["dispelName"] = "",--设置成激怒让默认显示(旁边怪有魔法容易乱)
				["duration"] = 20,--持续时间
				["expirationTime"] = GetTime()+20,--结束时间
			}
			unitFrame.RightAuras[aura.auraInstanceID] = aura;
			AddRightFrame(unitFrame,aura)
		end
	end
	if event == "UNIT_AURA" then
		if not unitFrame.RightAuras then
			init(unitFrame)
		end
		
		if unitAuraUpdateInfo.addedAuras ~= nil then
			for _, aura in ipairs(unitAuraUpdateInfo.addedAuras) do
				if filter(aura,unit) and aura.auraInstanceID ~= unitFrame.RightAuras[aura.auraInstanceID] then
				--不知道为什么新增的时候更新4次,所以这里多加了个判断,但依然更新2次,刷新也是
				if aura.auraInstanceID == unitFrame.RightAuras[aura.auraInstanceID] then return end
					unitFrame.RightAuras[aura.auraInstanceID] = aura;
					AddRightFrame(unitFrame, aura)
				end
			end
		end

		if unitAuraUpdateInfo.updatedAuraInstanceIDs ~= nil then
			for _, auraInstanceID in ipairs(unitAuraUpdateInfo.updatedAuraInstanceIDs) do
				if unitFrame.RightAuras[auraInstanceID] ~= nil then
					local newAura = C_UnitAuras.GetAuraDataByAuraInstanceID(unitFrame.unit, auraInstanceID);
					unitFrame.RightAuras[auraInstanceID] = newAura;
					AddRightFrame(unitFrame, newAura)
				end
			end
		end

		if unitAuraUpdateInfo.removedAuraInstanceIDs ~= nil then
			for _, auraInstanceID in ipairs(unitAuraUpdateInfo.removedAuraInstanceIDs) do
				if unitFrame.RightAuras[auraInstanceID] ~= nil then
					AddRightFrame(unitFrame, unitFrame.RightAuras[auraInstanceID],0)
					unitFrame.RightAuras[auraInstanceID] = nil;
					for key,aura in pairs(unitFrame.RightAuras) do
						--C_Timer.After(0.1,function()
							AddRightFrame(unitFrame,aura)
						--end)
					end
				end
			end
		end
	end	
end

local AurasEvent = CreateFrame('Frame')
AurasEvent:SetScript('OnEvent', UpdateAuras)
AurasEvent:RegisterEvent("UNIT_AURA")
AurasEvent:RegisterEvent("NAME_PLATE_UNIT_ADDED")